<script setup>
import { onMounted, ref, onUnmounted, reactive } from 'vue'
import HelloWorld from './components/HelloWorld.vue'
import watermark2 from './components/watermark2.vue'
// import * as THREE from 'three'
// import { TextGeometry } from 'three/addons/geometries/TextGeometry.js';
import Hls from 'hls.js'
const video_url = "https://sf1-cdn-tos.huoshanstatic.com/obj/media-fe/xgplayer_doc_video/hls/xgplayer-demo.m3u8"
// const video_url = "http://172.18.0.67:8021/video/m3u8?fileName=http://172.18.0.67:8021/video/test/hls.m3u8"
// const video_url = "https://test-streams.mux.dev/x36xhzz/x36xhzz.m3u8"
const viewType = 3
const video_src = ref(""), videoPlayer = ref(null)
onMounted(() => {
  if(viewType === 1) {
    console.log(videoPlayer.value)
    createDOM(video_url)
  }
})
// 组件卸载时清理
onUnmounted(() => {
  // observer.disconnect()
  // cancelAnimationFrame(animationFrameId)
})
function createDOM(url){
		let video = document.createElement('video')
		video.id = 'video'
		//如果需要全屏幕展现播放器需要增加 object-fit: cover;
		video.style = 'width: 100%; height: 100%;'
		video.controls = false
    video.setAttribute('disablepictureinpicture', true)
		video.setAttribute('playsinline', true) //IOS微信浏览器支持小窗内播放
		video.setAttribute('webkit-playsinline', true) //这个bai属性是ios 10中设置可以让视频在小du窗内播放，也就是不是全屏播放的video标签的一个属性
		video.setAttribute('x5-video-player-type', 'h5') //安卓 声明启用同层H5播放器 可以在video上面加东西
		let source = document.createElement('source')
		source.src = url  //设定的流地址
		//根据流地址的后缀设置好播放类型
		if (source.src.indexOf('.mp4') !== -1) {
		  //mp4类型
		  source.type = 'video/mp4'
		} else if (source.src.indexOf('.m3u8') !== -1) {
		  //hls类型
      console.log('hls')
		  // source.type = 'application/x-mpegURL'
      if (Hls.isSupported()) {
        const hls = new Hls()
        hls.loadSource(url)
        hls.attachMedia(video)
      } else if (video.canPlayType('application/vnd.apple.mpegurl')) {
        // Safari原生支持
        video.src = url
      }
		} else if (source.src.indexOf('.flv') !== -1) {
		  //flv类型
		  source.type = 'video/flv'
		} else {
		  //rtmp类型
		  source.type = 'rtmp/hls'
		}
		//将播放源添加到video的子级
		// video.appendChild(source) // 如果只有mu3u8流地址可以不添加这个


    // 创建水印画布 =====================================================
    let cssText = `
            display: block !important;
            visibility: visible !important;
            opacity: 1 !important;
            position: absolute !important;
            z-index: 999 !important;
            pointer-events: none !important;
            top: 0 !important;
          `
    const canvas = document.createElement('canvas')
    // 给canvas添加一个id
    canvas.id = 'watermark'
    canvas.style.cssText = cssText
    // 挂载到视频容器
    videoPlayer.value.appendChild(canvas)
    // 动态更新水印
    function updateWatermark() {
      if (!canvas || !video) return
  
      const ctx = canvas.getContext('2d')
      if (!ctx) {
        console.error('无法获取canvas上下文')
        return
      }


      canvas.width = video.offsetWidth
      canvas.height = video.offsetHeight
      
      // 铺满屏幕
      createDenseWatermark(ctx, canvas.width, canvas.height) // 绘制水印
      requestAnimationFrame(updateWatermark) // 递归调用
    }
    // 检查样式是否被修改
    function checkWatermarkStyle() {
      const check = () => {
        const computedStyle = getComputedStyle(canvas)
        const violations = [
          computedStyle.position !== 'absolute',
          computedStyle.display === 'none',
          computedStyle.visibility === 'hidden',
          computedStyle.top !== '0px !important',
          computedStyle.left !== '0px !important',
          computedStyle.right !== '0px !important',
          parseFloat(computedStyle.opacity) < 0.5
        ]

        if (violations.some(v => v)) { // 如果有违反，重新设置样式
          canvas.style.cssText = cssText
        }
      }
      // 每秒检查10次（平衡性能与安全性）
      setInterval(check, 100)
    }
    // 修改事件监听部分
    const initWatermark = () => {
      checkWatermarkStyle()
      updateWatermark()
    }
    // 同时监听多个初始化事件
    video.addEventListener('loadedmetadata', initWatermark) // 元数据加载完成
    video.addEventListener('canplay', initWatermark)        // 视频可播放时
    video.addEventListener('play', initWatermark)   // 视频播放时

    // 创建高密度水印
    let Angle = [-20, 20, 0]
    const randomIndexAngle = Math.floor(Math.random() * Angle.length)
    let x_w = [250, 300, 200, 180] // 水印横向间隔
    let randomX = Math.floor(Math.random() * x_w.length)
    let y_w = [150, 120, 180, 90] // 水印纵向间隔
    let randomY = Math.floor(Math.random() * y_w.length)
    function createDenseWatermark(ctx, width, height) {
      // 添加绘制验证
      // console.log('正在绘制水印，尺寸：', width, height)
      // ctx.fillStyle = 'red' // 临时测试颜色
      // ctx.fillRect(0, 0, 100, 30) // 测试绘制基本图形

      ctx.save() // 保存画布状态
      ctx.font = '18px Arial'
      ctx.fillStyle = 'rgba(255,255,255,0.3)'
      
      ctx.rotate(Angle[randomIndexAngle] * Math.PI / 180) // 旋转角度
      const timestamp = new Date().toLocaleTimeString()
      // 矩阵式重复水印
      for (let x = -width; x < width*2; x += x_w[randomX]) {
        for (let y = -height; y < height*2; y += y_w[randomY]) {
          // ctx.fillText(`ID:USER_${Date.now()}`, x, y)
          ctx.fillText(`ID:USER_${timestamp}`, x, y)
        }
      }
      ctx.restore() // 恢复画布状态
      // 添加全屏检测
      if (document.fullscreenElement) {
        ctx.font = '24px Arial' // 全屏时增大字号
      }
      
      // 添加绘制完成标记
      // ctx.fillStyle = 'green'
      // ctx.fillText('绘制完成', 10, 20)
    }
    
    // 使用MutationObserver保护水印元素不被f12删除
    const observer = new MutationObserver(mutations => {
      mutations.forEach(mutation => {
        // 防御display属性修改
        if (mutation.type === 'attributes' && mutation.attributeName === 'style') {
          const currentDisplay = getComputedStyle(canvas).display
          if (currentDisplay === 'none') {
            canvas.style.display = 'block'
          }
        }
        // 禁止在f12后对元素进行删除
        const fullscreenElement = document.fullscreenElement
        const targetContainer = fullscreenElement || videoPlayer.value
        if (!targetContainer.contains(canvas)) { // 如果canvas不在目标容器中，则重新添加
          targetContainer.appendChild(canvas)
        }

        // 判断是否是全屏
        // if (fullscreenElement) { // 全屏中
        //   // if(!fullscreenElement.contains(canvas)) {
        //   if(!document.body.contains(canvas)) {
        //     console.log('全屏中')
        //     document.body.appendChild(canvas)
        //   }
        // } else { // 未全屏
        //     // 获取类名是video-js的元素
        //     const video_box = document.querySelector('.video-js')
        //     if (!video_box.contains(canvas)) {
        //       videoPlayer.value.appendChild(canvas)
        //     }
        // }
      })
    })
    // 修改观察配置
    observer.observe(document.body, {
      attributes: true,         // 观察属性变化
      attributeFilter: ['style'], // 仅观察style属性
      childList: true,          // 原有子节点观察
      subtree: true             // 原有子树观察
    })

		//挂载到视频容器中
		videoPlayer.value.appendChild(video)

    // 全屏设置
    function handleFullscreenChange() {
      const fullscreenElement = document.fullscreenElement || 
                              document.webkitFullscreenElement ||
                              document.mozFullScreenElement
      if (fullscreenElement) {
        console.log('进入全屏状态')
        console.log(fullscreenElement.nodeName )
        // // 全屏时重新挂载水印
        // fullscreenElement.appendChild(canvas)
        // // 调整水印尺寸
        // canvas.width = fullscreenElement.offsetWidth
        // canvas.height = fullscreenElement.offsetHeight
        // // createDenseWatermark(canvas.getContext('2d'), canvas.width, canvas.height)
        // // 使用setTimeout等待浏览器渲染
        // setTimeout(() => {
        //   const ctx = canvas.getContext('2d')
        //   ctx.clearRect(0, 0, canvas.width, canvas.height)
        //   createDenseWatermark(ctx, canvas.width, canvas.height)
        // }, 500)
      } else {
        console.log('退出全屏状态')
        // 退出全屏时恢复位置
        videoPlayer.value.appendChild(canvas)
      }
    }
    // 添加全屏事件监听
    // document.addEventListener('fullscreenchange', handleFullscreenChange)
    // document.addEventListener('webkitfullscreenchange', handleFullscreenChange)
    // document.addEventListener('mozfullscreenchange', handleFullscreenChange)

    // 全屏逻辑修改
    videoPlayer.value.addEventListener('dblclick', () => {
      console.log('双击全屏')
      const fullscreenElement = document.fullscreenElement || 
                              document.webkitFullscreenElement ||
                              document.mozFullScreenElement
      console.log("fullscreenElement: ",fullscreenElement)
      if(fullscreenElement) { // 退出全屏
        document.exitFullscreen().catch(console.error)
      } else {
        videoPlayer.value.requestFullscreen().catch(console.error)
      }
    })
	}
  function addFunc() {
    // 在id test的元素上添加span元素
    let span = document.createElement('span')
    span.innerText = '添加的元素'
    span.style = 'color: red;'
    span.id = 'test_span'
    span.className = 'test_span'
    span.onclick = function() {
      console.log('点击了添加的元素')
    }
    let test = document.getElementById('test')
    test.appendChild(span)
  }
</script>

<template>
   <div>
    m3u8
    <div v-if="viewType===1" ref="videoPlayer" class="video-js" style="margin: auto auto;width: 100%;position:relative;"></div>
    <!-- <video ref="videoPlayer" id="vo" :src="video_src" controls autoplay style="width:100%"></video> -->
   <HelloWorld v-else-if="viewType===2"></HelloWorld>
   <watermark2 v-else />

   <div id="test" @click="addFunc">add</div>
   </div>
</template>

<style scoped>
.logo {
  height: 6em;
  padding: 1.5em;
  will-change: filter;
  transition: filter 300ms;
}
.logo:hover {
  filter: drop-shadow(0 0 2em #646cffaa);
}
.logo.vue:hover {
  filter: drop-shadow(0 0 2em #42b883aa);
}
/* 添加全局样式 */
/* .video-js::after {
  content: "Dynamic Watermark " attr(data-time);
  position: absolute;
  bottom: 50%;
  left: 50%;
  transform: translateX(-50%);
  color: rgba(255,255,255,0.5);
  font-size: 20px;
  pointer-events: none;
  z-index: 999;
} */
 /* 添加全局不可覆盖样式 */
#watermark {
  display: block !important;
  visibility: visible !important;
  opacity: 1 !important;
  pointer-events: none !important;
}

/* 全屏模式下的水印定位 */
:fullscreen #watermark,
:-webkit-full-screen #watermark,
:-moz-full-screen #watermark {
  position: fixed !important;
  width: 100vw !important;
  height: 100vh !important;
  top: 0 !important;
  left: 0 !important;
  z-index: 2147483647 !important; /* 最大z-index值 */
}
</style>
